package cpu.footprint.ui;

import android.app.Fragment;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import android.support.design.widget.*;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationConfiguration.LocationMode;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import cpu.footprint.R;
import cpu.footprint.api.AppXUtilDao;
import cpu.footprint.api.MyApplication;
import cpu.footprint.api.ResultMessage;
import cpu.footprint.bean.User;
import cpu.footprint.maptools.MyOrientationListener;
import cpu.footprint.maptools.PermissionUtil;

/**
 * Created by Administrator on 2017/3/7.
 */
@ContentView(R.layout.fragment_map)
public class MapFragment extends Fragment {
    @ViewInject(R.id.title_back)
    public ImageView title_back;//点击弹出左侧滑
    @ViewInject(R.id.title_content)
    public TextView title_content;//标题栏内容
    @ViewInject(R.id.title_menu_text)
    public TextView title_menu_text;//标题栏功能
    @ViewInject(R.id.title_menu_image)
    public ImageView title_menu_image;//标题栏功能
    @ViewInject(R.id.bmapView)
    public MapView mMapView;
    private ImageView image_view;//标题栏头像
    @ViewInject(R.id.image_centerMyAddress)
    private ImageView image_centerMyAddress;//回到我的位置
    public BaiduMap mBaiduMap;
    private BitmapDescriptor mIconLocation;
    private MyOrientationListener myOrientationListener;
    private float mCurrentx;
    private LocationClient mLocationClient;
    private LocationMode mLocationMode;
    private MapStatusUpdate msu;// 缩放级别
    private double mLatitude, mLongtitude;//当前位置的经纬度
    private double upLatitude = 0, upLongtitude = 0;//上次上传时位置的经纬度
    private Context mContext;
    private String filepath = Environment.getExternalStorageDirectory().getPath() + "/footprint/";
    private String[] mPermissions = new String[]{Manifest.permission.READ_PHONE_STATE, Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};
    public BDLocationListener myListener = new MyLocationListener();
    boolean isFirstLoc = true;
    private User user = new User();
    private boolean isLogin = false;
    private long nowTime = System.currentTimeMillis();
    private int flag=0;//(0:初始 无刷新无加载，1刷新 2加载更多)
    private Map<String, Object> map = new HashMap<String, Object>();
    private Handler mHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case ResultMessage.GET_INFO_SUCCESS: {
                    String jsonStr = msg.obj.toString();
                    JSONObject jsonObject = null;
//                    try {
//                        user= ApiJsonToUserModel.JsonToUserModel(jsonStr);
//                        LocalStorage.saveUserModel(mContext,user);
//                        initData();
//                        System.out.println("-------user: "+user.toString());
//                    } catch (JSONException e) {
//                        e.printStackTrace();
//                    }
                }
                break;
                case ResultMessage.GET_INFO_FAILED: {
                    ToastShow("身份验证失败，请重新登录！");
                    Intent intent = new Intent(mContext, LoginActivity.class);
                    intent.putExtra("IsLogin", false);
                    startActivity(intent);
                    getActivity().finish();
                }
                break;
                case ResultMessage.GET_HEAD_SUCCESS:
                    byte[] binaryData = (byte[]) msg.obj;
                    updateImage(binaryData);
                    break;
                case ResultMessage.GET_HEAD_FAILED:
                    ToastShow(msg.obj.toString());
                    break;
                case ResultMessage.FAILED:
                    ToastShow(msg.obj.toString());
                    break;
                case ResultMessage.TIMEOUT:
                    ToastShow(msg.obj.toString());
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    public View onCreateView(LayoutInflater inflater,
                              ViewGroup container,Bundle savedInstanceState) {
        SDKInitializer.initialize(getActivity().getApplicationContext());
        //  View view = inflater.inflate(R.layout.fragment_map, null);
        View view = x.view().inject(this, inflater, container);
        MyApplication app = (MyApplication) getActivity().getApplication();
        if (app.isLogin()) {
            user = app.getUser();
            isLogin = true;
        }
        initView(view);//初始化控件
        //上传足迹
        //CreateThreadUploadTrail();
        Bundle bundle = getArguments();
        if(bundle!=null){
            double activityLatitude=bundle.getDouble("activityLatitude",0);
            double activityLongitude=bundle.getDouble("activityLongitude",0);
            LatLng latLng=new LatLng(activityLatitude,activityLongitude);
            addMarker(latLng);
        }
        return view;
    }
    private void initView(View view) {
        title_back.setImageResource(R.mipmap.menu);
        title_content.setText("地图");
        title_menu_text.setVisibility(View.GONE);
        title_menu_image.setVisibility(View.GONE);
        mLocationClient = new LocationClient(getActivity().getApplicationContext());     //声明LocationClient类
        mLocationClient.registerLocationListener(myListener);    //注册监听函数
        mContext = getActivity();
        mMapView = (MapView) view.findViewById(R.id.bmapView);
        title_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MainActivity activity = (MainActivity) getActivity();
                activity.leftNavChange();//侧滑栏状态切换
            }
        });
        //版本判断
        System.out.println("------------->>>>Build.VERSION: " + Build.VERSION.SDK_INT);
        if (Build.VERSION.SDK_INT >= 23) {
            showContacts(mMapView);
        } else {
            initMapControls();
        }
        //mDialog= CreateDialogUtil.CreateDialog(getActivity(), "数据加载中...",mHandler);
    }

    /**
     * 初始化地图图层
     *
     * @param
     */
    private void initMapControls() {
        mMapView.setVisibility(View.VISIBLE);
        mBaiduMap = mMapView.getMap();
//        // 开启定位图层
        mBaiduMap.setMyLocationEnabled(true);
        msu = MapStatusUpdateFactory.zoomTo(16.0f);
        mBaiduMap.setMapStatus(msu);
        mMapView.showZoomControls(true);//默认放大缩小控件
        mMapView.showScaleControl(false);
        int count = mMapView.getChildCount();
        for (int i = 0; i < count; i++) {
            View child = mMapView.getChildAt(i);
            if (child instanceof ImageView) {
                // 隐藏百度地图logo
                child.setVisibility(View.INVISIBLE);
            }
        }
        initLocation();
    }

    /**
     * 添加覆盖物到地图
     * @param point
     */
    public void addMarker(LatLng point) {
        //定义Maker坐标点
//        LatLng poisnt = new LatLng(39.963175, 116.400244);
        //构建Marker图标
        BitmapDescriptor bitmap = BitmapDescriptorFactory
                .fromResource(R.mipmap.maker);
        //构建MarkerOption，用于在地图上添加Marker
        OverlayOptions option = new MarkerOptions()
                .position(point)
                .icon(bitmap);
        //在地图上添加Marker，并显示
        mBaiduMap.addOverlay(option);
        MapStatusUpdate msu = MapStatusUpdateFactory.newLatLng(point);
        mBaiduMap.animateMapStatus(msu);
    }

    // 返回当前定位
    private void centerToMyLocation() {
        LatLng latLng = new LatLng(mLatitude, mLongtitude);
        MapStatusUpdate msu = MapStatusUpdateFactory.newLatLng(latLng);
        mBaiduMap.animateMapStatus(msu);
    }

    /**
     * 初始化位置
     */
    private void initLocation() {
        mLocationMode = LocationMode.NORMAL;
        mLocationClient = new LocationClient(getActivity().getApplicationContext());
        myListener = new MyLocationListener();
        mLocationClient.registerLocationListener(myListener);
        LocationClientOption option = new LocationClientOption();
        option.setCoorType("bd09ll");
        option.setIsNeedAddress(true);
        option.setOpenGps(true);
        option.setScanSpan(3000);
        mLocationClient.setLocOption(option);
        mIconLocation = BitmapDescriptorFactory
                .fromResource(R.mipmap.map_location);
        myOrientationListener = new MyOrientationListener(getActivity());
        myOrientationListener
                .setOnOrientationListener(new MyOrientationListener.OnOrientationListener() {

                    @Override
                    public void onOrientationChanged(float x) {
                        // TODO Auto-generated method stub
                        mCurrentx = x;
                    }
                });
    }

    @Event(value = {R.id.title_back, R.id.image_centerMyAddress})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.title_back: {
                MainActivity activity = (MainActivity) getActivity();
                activity.leftNavChange();//切换侧滑栏的状态
            }
            break;
//            case R.id.activity_menu_title:{
//                Toast.makeText(mContext,"菜单",Toast.LENGTH_SHORT).show();
//            }break;
            case R.id.image_centerMyAddress: {
                centerToMyLocation();
            }
            break;
        }
    }

    /**
     * 定位监听类
     */
    private class MyLocationListener implements BDLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            MyLocationData data = new MyLocationData.Builder()//
                    .direction(mCurrentx).accuracy(location.getRadius())//
                    .latitude(location.getLatitude())//
                    .longitude(location.getLongitude())//
                    .build();
            mBaiduMap.setMyLocationData(data);
            mLatitude = location.getLatitude();
            mLongtitude = location.getLongitude();
            if (isFirstLoc) {
                isFirstLoc = false;
                MyLocationConfiguration config = new MyLocationConfiguration(
                        mLocationMode, true, mIconLocation);
                mBaiduMap.setMyLocationConfigeration(config);
                LatLng latLng = new LatLng(location.getLatitude(),
                        location.getLongitude());
                MapStatusUpdate msu = MapStatusUpdateFactory.newLatLng(latLng);
                mBaiduMap.animateMapStatus(msu);
            }
        }
    }

    private void CreateThreadUploadTrail() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        Thread.sleep(3000);
                        if (isLogin && upLatitude != mLatitude || upLongtitude != mLongtitude) {
                            upLatitude = mLatitude;
                            upLongtitude = mLongtitude;
                            map.clear();
                            map.put("groupId", user.getCurrentlyActiveId());
                            map.put("userId", user.getId());
                            map.put("longitude", mLongtitude);
                            map.put("latitude", mLatitude);
                            //mAppXUtilDao.UploadTrail(mHandler, map);
                            System.out.println("----------上传了");
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行mMapView.onDestroy()，实现地图生命周期管理
        mMapView.onDestroy();
    }

    @Override
    public void onStop() {
        // TODO Auto-generated method stub
        super.onStop();
        // 停止锟斤拷位
        mBaiduMap.setMyLocationEnabled(false);
        mLocationClient.stop();
        // 停止定位
        myOrientationListener.stop();
    }

    @Override
    public void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView. onResume ()，实现地图生命周期管理
        mMapView.setVisibility(View.VISIBLE);
        mMapView.onResume();
    }

    @Override
    public void onPause() {

        //在activity执行onPause时执行mMapView. onPause ()，实现地图生命周期管理
        mMapView.setVisibility(View.INVISIBLE);
        mMapView.onPause();
        super.onPause();
    }

    @Override
    public void onStart() {
        super.onStart();
        // 开始定位
        mBaiduMap.setMyLocationEnabled(true);
        if (mLocationClient != null) {
            if (!mLocationClient.isStarted())
                mLocationClient.start();
            // 锟斤拷锟斤拷锟斤拷锟津传革拷锟斤拷
        }
        myOrientationListener.start();
    }

    /**
     * 请求权限回调函数
     *
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {

        if (requestCode == 1) {
            if (PermissionUtil.verifyPermissions(grantResults)) {
                initMapControls();
            } else {
            }
        } else {
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    /**
     * 检查权限
     *
     * @param v
     */
    public void showContacts(View v) {
        Log.i("map", "Show contacts button pressed. Checking permissions.");
        // Verify that all required contact permissions have been granted.
        if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION)
                != PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(mContext, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(mContext, Manifest.permission.READ_PHONE_STATE)
                != PackageManager.PERMISSION_GRANTED) {
            // Contacts permissions have not been granted.
            Log.i("Map", "Contact permissions has NOT been granted. Requesting permissions.");
            requestContactsPermissions(v);

        } else {
            // Contact permissions have been granted. Show the contacts fragment.
            Log.i("Map",
                    "Contact permissions have already been granted. Displaying contact details.");
            initMapControls();
        }
    }

    /**
     * 请求权限
     *
     * @param v
     */
    private void requestContactsPermissions(View v) {
        if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
                Manifest.permission.ACCESS_COARSE_LOCATION)
                || ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
                Manifest.permission.ACCESS_FINE_LOCATION)
                || ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
                Manifest.permission.WRITE_EXTERNAL_STORAGE)
                || ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
                Manifest.permission.READ_PHONE_STATE)
                ) {
            Snackbar.make(v, "permission_contacts_rationale",
                    Snackbar.LENGTH_INDEFINITE)
                    .setAction("ok", new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            ActivityCompat
                                    .requestPermissions(getActivity(), mPermissions,
                                            1);
                        }
                    }).show();
        } else {
            ActivityCompat.requestPermissions(getActivity(), mPermissions, 1);
        }
    }

    void ToastShow(String text) {
        Toast.makeText(mContext, text, Toast.LENGTH_SHORT).show();
    }

    /**
     * 更新头像
     *
     * @param data
     */
    public void updateImage(byte[] data) {
        Bitmap result = BitmapFactory.decodeByteArray(data, 0, data.length);
        MainActivity activity = (MainActivity) getActivity();
        activity.image_head.setImageBitmap(result);
//        if(image_view!=null)
//            image_view.setImageBitmap(result);
        result.recycle();
        // head=result;
    }
}
